import { useState, useEffect } from 'react'
import type { FC, Key } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Button, Space, Table, Tag, Image } from 'antd'
import type { TableProps } from 'antd'

interface IProps {
  total: number
  data: IUserType.IUserItem[]
  loadData: (page: number, query: Record<string, any>) => void
  selectedRowKeys: Key[]
  changeSelectedRowKeys: (keys: Key[]) => void
}

// 自定义表单标题及显示字段的名称
const columns: TableProps<IUserType.IUserItem>['columns'] = [
  {
    // 表格显示的名称
    title: '账号',
    // 数据的字段名称
    dataIndex: 'username'
    // 自定义单元格显示内容，可以不写
    // 回调函数，参数1，当前单元格的数据，参数2此行的数据对象
    // render: (text,record) => <a>{text}</a>
  },
  {
    title: '姓名',
    dataIndex: 'realname'
  },
  {
    title: '年龄',
    dataIndex: 'age'
  },
  {
    title: '性别',
    dataIndex: 'sex',
    render: (text: number) => {
      if (text == 1) {
        return <Tag color="#108ee9">先生</Tag>
      }
      return <Tag color="#f50">女士</Tag>
    }
  },
  {
    title: '生日',
    dataIndex: 'birthday'
  },
  {
    title: '籍贯',
    dataIndex: 'city',
    render: (text: string[]) => {
      return text.join(' - ')
    }
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    render: (text: string) => {
      return <Image width={50} src={text} />
    }
  },
  {
    title: '操作',
    render: (_, record) => (
      <Space size="middle">
        <Button size="small" type="primary">
          修改
        </Button>
        <Button size="small" type="primary" danger>
          删除
        </Button>
      </Space>
    )
  }
]

const TableUser: FC<IProps> = ({
  total,
  data,
  loadData,
  selectedRowKeys,
  changeSelectedRowKeys
}) => {
  const [loading, setLoading] = useState(() => false)
  useEffect(() => {
    setLoading(data.length == 0)
  }, [data])
  // search字符串处理
  const [search, setSearch] = useSearchParams()
  const query = Object.fromEntries(search.entries())

  return (
    <>
      <Table
        loading={loading}
        rowKey={(record) => record.id}
        rowSelection={{
          selectedRowKeys,
          onChange: changeSelectedRowKeys
        }}
        columns={columns}
        dataSource={data}
        pagination={{
          current: query.page ? Number(query.page) : 1,
          size: 'default',
          position: ['bottomLeft'],
          total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总记录数： ${total} 位用户`,
          onChange: async (page) => {
            setLoading(true)
            // console.log('切换到的页 ', page)
            await loadData(page, query)
            setSearch({ ...query, page: String(page) })
            setLoading(false)
          },
          onShowSizeChange: (current, size) => {
            // console.log(current, size)
          }
        }}
      />
    </>
  )
}

export default TableUser
